#include "sockthread.h"

#include <QtNetwork>
QString filesize( double bytes )
{
    double mod = 1024, i = 0;
    QStringList formats;
    formats << "B" << "KB" << "MB" << "GB" << "TB" << "PB";
    for( ; bytes > mod; i++)
    {
        bytes /= mod;
    }
    return QString("%1 %2").arg( bytes ).arg( formats.at(i) );
}

sockThread::sockThread(int socketDescriptor, QObject *parent, QString directory, int upLimit, int dwLimit )
    : QThread(parent), socketDescriptor(socketDescriptor), directory(directory),
    upLimit(upLimit), dwLimit(dwLimit)
{
}

void sockThread::run()
{
    //QTcpSocket tcpSocket;
    QTcpSocket tcpSocket;

    if (! tcpSocket.setSocketDescriptor(socketDescriptor) ) {
        emit error(tcpSocket.error());
        return;
    }

    tcpSocket.waitForReadyRead();
    QByteArray request( tcpSocket.readAll() );
    QString requestHead( request );
    QStringList headers( requestHead.split("\r\n") );
    request.clear();

    QString path(
            QUrl::fromPercentEncoding(
                    QString(
                            QStringList(
                                    QString(
                                            headers.at(0)
                                            ).split(" ")
                                    ).at(1)
                            ).toAscii()
                    )
            );
    qDebug() << path;

    QByteArray response;
    if ( path.endsWith("/") )
    {
        plugDirectory dir( directory, path );
        response = dir.listDir();
        tcpSocket.write( response );
    }
    else
    {
        QFile file( directory + path );

        if( file.exists() )
        {
            QFreeDesktopMime mime;

            response.append("HTTP/1.1 200 OK");
            response.append("\r\n");
            response.append("Server: HTTPSrv");
            response.append("\r\n");
            response.append(QString("Content-Length: %1").arg( file.size() ));
            response.append("\r\n");
            response.append( QString("Content-Type: %1").arg( mime.fromFileName( file.fileName().toLower() ) ) );
            response.append("\r\n");
            response.append("\r\n");
            tcpSocket.write( response );
            qDebug() << mime.fromFileName(file.fileName()) << mime.expandedAcronym( mime.fromFileName(file.fileName()) );

            if (file.open(QFile::ReadOnly)) {
                 QByteArray buf;
                 int totalRead = 0;

                 while( file.size() > totalRead )
                 {
                     buf = file.readLine();
                     tcpSocket.write( buf );
                     tcpSocket.flush();
                     totalRead += buf.size();
                     buf.clear();
                 }
             }

        } else {
            QString text = QString("File %1 was not found on the server.").arg(path);

            response.append("HTTP/1.1 404 Not found");
            response.append("\r\n");
            response.append("Server: HTTPSrv");
            response.append("\r\n");
            response.append(QString("Content-lenght: %1").arg( text.size() ) );
            response.append("\r\n");
            response.append("Content-Type: text/plain; charset=utf-8");
            response.append("\r\n");
            response.append("\r\n");
            response.append( text );
            tcpSocket.write( response );
        }
    }

    tcpSocket.disconnectFromHost();
    if(tcpSocket.isOpen())
        tcpSocket.waitForDisconnected();
}

void sockThread::readRequest( )
{
    /*

    */
}

void sockThread::writeResponse()
{
}
